<script setup lang="ts">
import type { StudentWordItem, StudentWordReviewStudyRequestParams } from '@/api/types/student'
import type { WordWithStatus } from '@/pages/wordStudy/type'
import { handleApiError } from '@/api'
import { studentApi } from '@/api/modules/student'
import NavBar from '@/components/NavBar/index.vue'
import { useStudyWords } from '@/composables/useStudyWords'
import { useCurrentStudentInfoStore } from '@/stores/modules/useCurrentStudentInfoStore'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { calculateDurationInSeconds } from '@/utils/date'
import { formatDate } from '@/utils/format'
import { navigateBack } from '@/utils/navigation'
import { computed, onMounted, ref } from 'vue'
import AfterCheckWord from './components/AfterCheckWord.vue'
import ConfirmDialog from './components/ConfirmDialog.vue'
import ExitDialog from './components/ExitDialog.vue'
import HeaderTips from './components/HeaderTips.vue'
import UnfinishedDialog from './components/UnfinishedDialog.vue'

const studentInfoStore = useCurrentStudentInfoStore()
const unitStudyWordsStore = useUnitStudyWordsStore()
const exitDialogRef = ref()
const confirmDialogRef = ref()
const unfinishedDialogRef = ref()
const correctRate = ref(0)
const hasNextUnit = ref(false)

const {
  localWords,
  initStudyWords,
  updateWordClickNum,
} = useStudyWords()

// 初始化本地数据
onMounted(() => {
  unitStudyWordsStore.updateStudyStartTime()
  initStudyWords(unitStudyWordsStore.allGroupWords)
})

function handleWordClick(word: StudentWordItem) {
  console.log('word', word.wordId)
  updateWordClickNum(word.wordId)
}

function handleHeaderLeftClick() {
  exitDialogRef.value.openDialog()
}

async function postStudyWords() {
  const endTime = formatDate(new Date())
  const duration = calculateDurationInSeconds(unitStudyWordsStore.commonRequestParams.startTime, endTime)

  const params: StudentWordReviewStudyRequestParams = {
    studentId: unitStudyWordsStore.commonRequestParams.studentId,
    courseId: unitStudyWordsStore.commonRequestParams.courseId,
    unitNo: unitStudyWordsStore.commonRequestParams.unitNo,
    startTime: unitStudyWordsStore.commonRequestParams.startTime,
    lessonId: studentInfoStore.lessonId,
    endTime,
    duration,
    words: localWords.value.map((item) => {
    //   const degree = item.known === null ? WordDegree.UNKNOWN : WordDegree.KNOWN
      return {
        wordId: item.wordId,
        clickNum: item.clickNum || 0,
        correctNum: item.known ? 1 : 0,
        wrongNum: item.known ? 0 : 1,
        // degree: item.known === null ? WordDegree.UNKNOWN : WordDegree.KNOWN,
      }
    }),
  }
  const isReviewEntry = unitStudyWordsStore.isReviewEntry
  const [error, result] = isReviewEntry ? await studentApi.postReviewStudy(params) : await studentApi.shorthandPostStudy(params)
  if (error) {
    return handleApiError(error)
  }

  hasNextUnit.value = Boolean(result.data.nextUnitNo)
  // 如果存在下一单元 更新单元号的请求参数
  if (hasNextUnit.value) {
    unitStudyWordsStore.updateUnitNo(result.data.nextUnitNo)
  }
}

// 函数获取正确率
function getCorrectRate(words: WordWithStatus[]) {
  return words.filter(w => w.known === true).length / words.length * 100
}

async function onConfirm(words: WordWithStatus[]) {
  // 是否存在未标记的
  const isExistUnknown = words.some(w => w.known === null)
  if (isExistUnknown) {
    return unfinishedDialogRef.value.openDialog()
  }

  await postStudyWords()
  correctRate.value = getCorrectRate(words)
  return confirmDialogRef.value.openDialog()
}

function onUnfinishedConfirm() {
  console.log('用户已确认未完成提示')
}

const confirmButtons = computed(() => {
  if (!hasNextUnit.value) {
    return [
      {
        text: '返回',
        type: 'default',
        onClick: () => {
          navigateBack()
        },
      },
    ]
  }

  return [
    {
      text: '返回',
      type: 'default',
      onClick: () => {
        navigateBack()
      },
    },
    {
      text: '下一个单元',
      type: 'primary',
      onClick: async () => {
        unitStudyWordsStore.startPreCheckStudy({
          ...unitStudyWordsStore.commonRequestParams,
          lessonId: studentInfoStore.lessonId,
        })
      },
    },
  ]
})
</script>

<template>
  <view class="after-check">
    <NavBar title="学后检查" @left-click="handleHeaderLeftClick" />
    <HeaderTips>3秒内不认识的单词，标记为不会，系统将帮助你记忆巩固哦</HeaderTips>

    <ExitDialog ref="exitDialogRef" />
    <UnfinishedDialog ref="unfinishedDialogRef" @confirm="onUnfinishedConfirm" />
    <ConfirmDialog ref="confirmDialogRef" :buttons="confirmButtons" :correct-rate="correctRate" />

    <AfterCheckWord
      :words="localWords"
      @on-confirm="onConfirm"
      @word-click="handleWordClick"
    />
  </view>
</template>

<style lang="scss" scoped>
.after-check{
    padding-bottom: 120rpx;
}
</style>
